/*
* Name: TouchHandle.cpp
* Created by 勇 on 2022/11/16.
* Description: 触摸按键处理
*
*/
#include "TouchHandle.h"

unsigned long clickTime = 0;

unsigned long clickTime_tow = 0;

unsigned long clickTime_three = 0;


/**
 * pin esp8266引脚
 * activeLow: true 按下为低电平, false 按下为高电平
 * pullupActive: 如果没有上拉电阻就激活上拉电阻
 */
OneButton touch[SWITCH_NUMBER];

/**
 * 触摸按键引脚
 */
uint8_t touchPin[SWITCH_NUMBER] = {D0, D5, D6};

/**
 * 初始化触摸按键
 */
void initTouchButton() {
    // 初始化单击
    for (int i = 0; i < SWITCH_NUMBER; i++) {
        touch[i] = OneButton(touchPin[i], false, false);
        touch[i].attachClick(touchClickHandle,(void*)(long)i);
    }
    // 触摸按键1 设置长按事件
    touch[0].attachLongPressStart(touchLongClickStart);
    touch[0].attachLongPressStop(touchLongClickStop);

    // 触摸按键2 设置长按事件
    touch[1].attachLongPressStart(towTouchLongClickStart);
    touch[1].attachLongPressStop(towTouchLongClickStop);

    // 触摸按键3 设置长按事件
    touch[2].attachLongPressStart(threeTouchLongClickStart);
    touch[2].attachLongPressStop(threeTouchLongClickStop);

}

/**
 * 触摸按键轮询
 */
void touchCheck() {
    for (int i = 0; i < SWITCH_NUMBER; i++) {
        touch[i].tick();
    }
}


/**
 * 触摸按键 单击处理
 * 0=开关1,1=开关2,2=开关3
 * @param num
 */
void touchClickHandle(void *num) {
    // 判断不是无工作模式,直接返回
    if (getWorkMode() != WORK_MODE_NULL)
        return;
    int number = (int) (long) num;
    switch (number) {
        case 0:
            setWorkMode(WORK_MODE_SWITCH_ONE);
            break;
        case 1:
            setWorkMode(WORK_MODE_SWITCH_TOW);
            break;
        case 2:
            setWorkMode(WORK_MODE_SWITCH_THREE);
            break;
    }
}

/**
 * 触摸按键1 长按开始
 */
void touchLongClickStart() {
    clickTime = millis();
}

/**
 * 触摸按键1 长按结束
 */
void touchLongClickStop() {
    if (getWorkMode() != WORK_MODE_NULL)
        return;
    if (millis() - clickTime >= LONG_CLICK_EVENT_TIME_OUT) {
        setWorkMode(WORK_MODE_SET_WIFI_CONFIG);
    }
}


/**
 * 触摸按键2 长按开始
 */
void towTouchLongClickStart(){
    clickTime_tow = millis();
}

/**
 * 触摸按键2 长按结束
 */
void towTouchLongClickStop(){
    if(getWorkMode() != WORK_MODE_NULL)
        return;
    if(millis() - clickTime_tow >= LONG_CLICK_EVENT_TIME_OUT){
        setWorkMode(WORK_MODE_SET_WIFI_WEB_CONFIG);
    }
}


/**
 * 触摸按键3 长按开始
 */
void threeTouchLongClickStart(){
    clickTime_three = millis();
}

/**
 * 触摸按键3 长按结束
 */
void threeTouchLongClickStop(){
    // 重启的话不需要判断, 直接重启
    // if(getWorkMode() != WORK_MODE_NULL)
    //     return;
    if(millis() - clickTime_three >= LONG_CLICK_EVENT_TIME_OUT){
        setWorkMode(WORK_MODE_RESTART);
    }
}